<?php

namespace app\admin\controller;

class Link extends Common
{
    public function index()
    {
        if (request()->isPost()) {
            $val = input('post.val');
            $map = '';
            if (!empty($val)) {
                $map['name|url'] = ['like', "%" . $val . "%"];
            }
            $link = db('links')->where($map)->order('sort')->select();
            foreach ($link as $k => $v) {
                $link[$k]['create_time'] = date('Y-m-d H:s', $v['create_time']);
            }
            return ['code' => 0, 'msg' => '获取成功!', 'data' => $link];
        }
        return $this->fetch();
    }
    
    //修改友情链接状态
    public function linkState()
    {
        $id = input('post.id');
        $open = input('post.open');
        if (db('links')->where('id=' . $id)->update(['open' => $open]) !== false) {
            return ['status' => 1, 'msg' => '设置成功!'];
        } else {
            return ['status' => 0, 'msg' => '设置失败!'];
        }
    }
    
    public function listOrder()
    {
        $data = input('post.');
        if (db('links')->update($data) !== false) {
            cache('linkList', null);
            return ['msg' => '操作成功！', 'url' => url('index'), 'code' => 1];
        } else {
            return ['code' => 0, 'msg' => '操作失败！'];
        }
    }
    
    //添加
    public function add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $data['create_time'] = time();
            db('links')->insert($data);
            $result['code'] = 1;
            $result['msg'] = '友情链接添加成功!';
            $result['url'] = url('index');
            cache('linkList', null);
            return $result;
        } else {
            $this->assign('title', lang('add') . lang('link'));
            $this->assign('info', 'null');
            return $this->fetch('edit');
        }
    }
    
    //修改友情链接
    public function edit()
    {
        if (request()->isPost()) {
            $data = input('post.');
            db('links')->update($data);
            $result['code'] = 1;
            $result['msg'] = '友情链接修改成功!';
            $result['url'] = url('index');
            cache('linkList', null);
            return $result;
        } else {
            $id = input('param.id');
            $info = db('links')->where(['id' => $id])->find();
            $this->assign('info', $info);
            $this->assign('title', lang('edit') . lang('link'));
            return $this->fetch('edit');
        }
    }
    
    public function del()
    {
        db('links')->where(['id' => input('id')])->delete();
        cache('linkList', null);
        return ['code' => 1, 'msg' => '删除成功！'];
    }
    
    public function delall()
    {
        $map[] = ['id', 'IN', input('param.ids/a')];
        db('links')->where($map)->delete();
        $result['msg'] = '删除成功！';
        $result['code'] = 1;
        $result['url'] = url('index');
        cache('linkList', null);
        return $result;
    }
}